<template>
  <div>
    <el-dialog
      v-model="show"
      :title=" menuParams._id ? '修改菜单' : '添加菜单'"
      width="500"
      center
      draggable
      overflow
      :close-on-click-modal="false"
      @close="closeHandler"
    >
     <el-form :model="menuParams" :rules="rules" ref="form" label-width="120px" >
       <el-form-item label="菜单名称" prop="mName">
        <el-input v-model="menuParams.mName" placeholder="请输入菜单名称" clearable></el-input>
       </el-form-item>
       <el-form-item label="菜单值" prop="mValue">
        <el-input v-model="menuParams.mValue" placeholder="请输入菜单值" clearable></el-input>
       </el-form-item>
     </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeHandler">取消</el-button>
          <el-button type="primary" @click="addOrUpdateMenu"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive , watch , onMounted } from "vue";
import { AddOrUpdateMenuAPI } from '@/api/menu'
import { ElMessage } from 'element-plus'
defineOptions({
  name: "AddOrUpdate",
});
const props = defineProps(["modelValue" , "getMenuList" , "updateInfo"]);
const emits = defineEmits(["update:modelValue"]);
const show = ref(props.modelValue);
let menuParams = reactive({
    mName:'',
    mValue:''
})

let rules = reactive({
    mName:[
        {required:true,message:'请输入菜单名称',trigger:'blur'},
        {min:3,max:10,message:'长度在3到10个字符',trigger:'blur'}
    ],
    mValue:[
        {required:true,message:'请输入菜单值',trigger:'blur'},
        {min:3,max:20,message:'长度在3到20个字符',trigger:'blur'}
    ]
})
let form = ref(null)
watch(
  () => props.modelValue,
  (newValue) => {
    show.value = newValue;
  }
);
watch(()=>props.updateInfo,(newValue)=>{
  Object.assign(menuParams,newValue)
})
const closeHandler = () => {
  show.value = false;
  emits("update:modelValue", false);
  form.value.resetFields()
  Object.assign(menuParams,{
    _id:'',
    mName:'',
    mValue:''
  })
};
const addOrUpdateMenu = async ()=>{
    await form.value.validate()
    await AddOrUpdateMenuAPI(menuParams)
    
    if(menuParams._id) {
      ElMessage.success('修改成功')
    }else {
      ElMessage.success('添加成功')
    }
    closeHandler()
    props.getMenuList()
}
</script>

<style lang="scss" scoped></style>
